<template>
  <view class="uni-file-picker">
    <view v-if="title" class="uni-file-picker__header">
      <text class="file-title">{{ title }}</text>
      <text class="file-count">{{ files.length }}/{{ limitLength }}</text>
    </view>
    <upload-image v-if="fileMediatype === 'image' && showType === 'grid'" :readonly="readonly"
      :image-styles="imageStyles" :files-list="files" :limit="limitLength" :disablePreview="false" :delIcon="delIcon"
      @choose="choose" @delFile="delFile">
      <slot>
        <view class="is-add">
          <view class="icon-add"></view>
          <view class="icon-add rotate"></view>
        </view>
      </slot>
    </upload-image>
    <upload-file v-if="fileMediatype !== 'image' || showType !== 'grid'" :readonly="readonly" :list-styles="listStyles"
      :files-list="files" :showType="showType" :delIcon="delIcon" @choose="choose" @delFile="delFile">
      <slot><button type="primary" size="mini">选择文件</button></slot>
    </upload-file>


    <uni-drawer class="insert-image-drawer" v-if="drawerWidth" ref="unifySourceDrawer" mode="right"
      :width="drawerWidth">
      <unify-source :media-tabs="[fileMediatype]" mode="picker" @onInsert="onSourceInsert" :selected-count="limit" />
    </uni-drawer>
  </view>
</template>

<script>
  import {
    chooseAndUploadFile,
    uploadCloudFiles
  } from './choose-and-upload-file.js'
  import {
    get_file_ext,
    get_extname,
    get_files_and_is_max,
    get_file_info,
    get_file_data
  } from './utils.js'
  import uploadImage from './upload-image.vue'
  import uploadFile from './upload-file.vue'
  let fileInput = null
  /**
   * @property {Boolean}	disabled = [true|false]	组件禁用
   * 	@value true 	禁用
   * 	@value false 	取消禁用
   * @property {Boolean}	readonly = [true|false]	组件只读，不可选择，不显示进度，不显示删除按钮
   * 	@value true 	只读
   * 	@value false 	取消只读
   * @property {Boolean}	del-icon = [true|false]	是否显示删除按钮
   * 	@value true 	显示删除按钮
   * 	@value false 	不显示删除按钮
   * @property {Number|String}	limit	最大选择个数 ，h5 会自动忽略多选的部分
   * @property {String}	title	组件标题，右侧显示上传计数
   * @property {String}	mode = [list|grid]	选择文件后的文件列表样式
   * 	@value list 	列表显示
   * 	@value grid 	宫格显示
   * @property {String}	file-mediatype = [image|video|all]	选择文件类型
   * 	@value image	只选择图片
   * 	@value video	只选择视频
   * 	@value all		选择所有文件
   * @property {Array}	file-extname	选择文件后缀，根据 file-mediatype 属性而不同
   * @property {Object}	list-style	mode:list 时的样式
   * @property {Object}	image-styles	选择文件后缀，根据 file-mediatype 属性而不同
   */
  export default {
    name: 'unifySourcePicker',
    components: {
      uploadImage,
      uploadFile
    },
    options: {
      virtualHost: true
    },
    emits: ['update:modelValue'],
    props: {
      modelValue: {
        type: [Array, String],
        default () {
          return []
        }
      },
      disabled: {
        type: Boolean,
        default: false
      },
      delIcon: {
        type: Boolean,
        default: true
      },
      // 最大选择个数 ，h5只能限制单选或是多选
      limit: {
        type: [Number, String],
        default: 9
      },
      // 列表样式 grid | list | list-card
      mode: {
        type: String,
        default: 'grid'
      },
      // 选择文件类型  image/video/all
      fileMediatype: {
        type: String,
        default: 'image'
      },
      title: {
        type: String,
        default: ''
      },
      listStyles: {
        type: Object,
        default () {
          return {
            // 是否显示边框
            border: true,
            // 是否显示分隔线
            dividline: true,
            // 线条样式
            borderStyle: {}
          }
        }
      },
      imageStyles: {
        type: Object,
        default () {
          return {
            width: 'auto',
            height: 'auto'
          }
        }
      },
      readonly: {
        type: Boolean,
        default: false
      },
      returnType: {
        type: String,
        default: 'array'
      },
      adapter:{
        type:Object,
        default:function(item){
          return item
        }
      }
    },
    data() {
      return {
        files: [],
        localValue: [],
        drawerWidth: 0,
      }
    },
    computed: {
      showType() {
        if (this.fileMediatype === 'image') {
          return this.mode
        }
        return 'list'
      },
      limitLength() {
        if (this.returnType === 'object') {
          return 1
        }
        if (!this.limit) {
          return 1
        }
        if (this.limit >= 9) {
          return 9
        }
        return this.limit
      },
      returnValue() {
        if (this.files.length) {
          return this.adapter(this.files.map(item => {
            return item.url
          }));
        } else {
          return null;
        }
      }
    },
    watch: {
      modelValue: {
        handler(newValue) {
          console.log(newValue);
          if(newValue == null){
            return;
          }
          if(typeof newValue == "string"){
            newValue = [newValue]
          }
          
          this.files = newValue.map(item => {
            return {
              url:item,
            }
          });
        },
        immediate: true
      }
    },
    mounted() {
      const sysinfo = uni.getSystemInfoSync()
      this.drawerWidth = sysinfo.windowWidth * .85
    },
    methods: {
      onSourceInsert(files) {
        this.files = this.files.concat(files);
        this.$refs.unifySourceDrawer.close();
        
        this.$emit('update:modelValue', this.returnValue)

      },
      choose() {
        this.$refs.unifySourceDrawer.open();
      },

      /**
       * 删除文件
       * @param {Object} index
       */
      delFile(index) {
        this.files.splice(index, 1)
        this.$nextTick(() => {
          this.$emit('update:modelValue', this.returnValue)
        })
      },
    }
  }
</script>

<style>
  .uni-file-picker {
    /* #ifndef APP-NVUE */
    box-sizing: border-box;
    overflow: hidden;
    width: 100%;
    /* #endif */
    flex: 1;
  }

  .uni-file-picker__header {
    padding-top: 5px;
    padding-bottom: 10px;
    /* #ifndef APP-NVUE */
    display: flex;
    /* #endif */
    justify-content: space-between;
  }

  .file-title {
    font-size: 14px;
    color: #333;
  }

  .file-count {
    font-size: 14px;
    color: #999;
  }

  .is-add {
    /* #ifndef APP-NVUE */
    display: flex;
    /* #endif */
    align-items: center;
    justify-content: center;
  }

  .icon-add {
    width: 50px;
    height: 5px;
    background-color: #f1f1f1;
    border-radius: 2px;
  }

  .rotate {
    position: absolute;
    transform: rotate(90deg);
  }
</style>